<script setup>
import { ref, onMounted, onActivated } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import StatusTag from '@/components/common/StatusTag.vue'
import ApprovalTimeline from '@/components/leave/ApprovalTimeline.vue'
import FloatingBackButton from '@/components/common/FloatingBackButton.vue'
import LogoutButton from '@/components/common/LogoutButton.vue'
import { getTeacherLeaveDetail, approveLeave } from '@/api'

const route = useRoute()
const router = useRouter()
const id = route.params.id

const loading = ref(false)
const detail = ref(null)
const steps = ref([])
const comment = ref('')
const submitting = ref(false)

// 获取请假详情
const fetchDetail = async () => {
  loading.value = true
  try {
    const response = await getTeacherLeaveDetail(id)
    if (response.code === 0 && response.data) {
      const data = response.data
      detail.value = {
        studentName: data.student_name || '未知',
        studentNo: data.student_id || '',
        typeLabel: data.type === 'sick' ? '病假' : data.type === 'personal' ? '事假' : '其他',
        timeRange: `${formatDateTime(data.start_at)} ~ ${formatDateTime(data.end_at)}`,
        hours: data.hours,
        status: data.status,
        reason: data.reason,
      }

      // 转换审批步骤
      steps.value = (data.steps || []).map((step) => ({
        title: step.title,
        time: step.acted_at ? formatDateTime(step.acted_at) : '—',
        comment: step.comment || '待处理',
        status: step.status,
      }))
    }
  } catch (error) {
    console.error('获取详情失败:', error)
  } finally {
    loading.value = false
  }
}

// 格式化时间
const formatDateTime = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `2025-${month}-${day} ${hours}:${minutes}`
}

// 审批操作
const handleApprove = async (approved) => {
  const action = approved ? '通过' : '驳回'
  if (!confirm(`确定要${action}这条请假申请吗？`)) return

  if (!comment.value.trim()) {
    alert('请填写审批意见')
    return
  }

  submitting.value = true
  try {
    const response = await approveLeave(id, {
      approved,
      comment: comment.value.trim(),
    })

    if (response.code === 0) {
      alert(`✅ 审批${action}成功！`)
      router.replace('/teacher/approvals')
    } else {
      alert(`❌ ${response.message || `${action}失败`}`)
    }
  } catch (error) {
    console.error(`${action}失败:`, error)
    alert(`❌ ${error.message || `${action}失败`}`)
  } finally {
    submitting.value = false
  }
}

onMounted(() => {
  fetchDetail()
})

// 每次页面激活时刷新数据
onActivated(() => {
  fetchDetail()
})
</script>

<template>
  <div class="page">
    <div class="container">
      <div class="header">
        <h2>审批详情</h2>
      </div>

      <div v-if="loading" class="loading-text">加载中...</div>
      <template v-else-if="detail">
        <div class="grid">
          <div class="card elevated">
            <div class="row">
              <strong>{{ detail.studentName }}</strong
              ><small>ID: {{ detail.studentNo }}</small>
            </div>
            <div class="row">
              <span>{{ detail.typeLabel }}</span
              ><StatusTag :status="detail.status" />
            </div>
            <div class="kv">
              <span>时间段</span><b>{{ detail.timeRange }}</b>
            </div>
            <div class="kv">
              <span>时长(小时)</span><b>{{ detail.hours }}</b>
            </div>
            <div class="kv">
              <span>事由</span><b>{{ detail.reason }}</b>
            </div>
          </div>
          <div class="card elevated">
            <h3 class="section-title">审批进度</h3>
            <ApprovalTimeline :steps="steps" />
          </div>
        </div>

        <!-- 审批操作（仅待审批状态显示） -->
        <div v-if="detail.status === 'pending'" class="approve-card card elevated">
          <h3>审批操作</h3>
          <div class="field">
            <label>审批意见</label>
            <textarea v-model="comment" placeholder="请输入审批意见（必填）" rows="4"></textarea>
          </div>
          <div class="btn-row">
            <button class="btn danger" :disabled="submitting" @click="handleApprove(false)">
              {{ submitting ? '处理中...' : '驳回' }}
            </button>
            <button class="btn success" :disabled="submitting" @click="handleApprove(true)">
              {{ submitting ? '处理中...' : '通过' }}
            </button>
          </div>
        </div>
      </template>
      <div v-else class="error-text">加载失败</div>
    </div>
    <FloatingBackButton />
    <LogoutButton />
  </div>
</template>

<style scoped>
.page {
  position: fixed;
  inset: 0;
  padding: 32px 24px;
  overflow: auto;
  background:
    radial-gradient(circle at 20% 10%, rgba(255, 105, 0, 0.04) 0%, transparent 40%),
    radial-gradient(circle at 80% 90%, rgba(255, 105, 0, 0.04) 0%, transparent 40%);
}
.container {
  width: 100%;
  max-width: 1120px;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  gap: 16px;
}
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.btn.success {
  background: var(--color-success);
  color: #fff;
  border: none;
  padding: 10px 14px;
  border-radius: 8px;
  font-weight: 700;
  cursor: pointer;
}
.btn.danger {
  background: var(--color-danger);
  color: #fff;
  border: none;
  padding: 10px 14px;
  border-radius: 8px;
  font-weight: 700;
  cursor: pointer;
}
.grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}
.card {
  background: #fff;
  border: 1px solid rgba(0, 0, 0, 0.06);
  border-radius: 16px;
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}
.elevated {
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.06);
}
.row {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.kv {
  display: grid;
  grid-template-columns: 120px 1fr;
  gap: 8px;
  align-items: center;
}
.kv span {
  color: var(--muted-text);
}
.section-title {
  font-size: 16px;
  margin-bottom: 8px;
}
.loading-text,
.error-text {
  text-align: center;
  padding: 40px;
  color: #999;
  font-size: 14px;
}
.approve-card {
  padding: 24px;
}
.approve-card h3 {
  font-size: 16px;
  margin-bottom: 16px;
}
.field {
  margin-bottom: 16px;
}
.field label {
  display: block;
  margin-bottom: 8px;
  font-weight: 600;
  color: #1d1d1f;
}
.field textarea {
  width: 100%;
  padding: 12px;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  font-size: 14px;
  font-family: inherit;
  resize: vertical;
}
.field textarea:focus {
  outline: none;
  border-color: var(--color-primary);
}
.btn-row {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}
.btn {
  padding: 10px 24px;
  border: none;
  border-radius: 8px;
  font-weight: 600;
  cursor: pointer;
  font-size: 14px;
}
.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}
.btn.success {
  background: var(--color-success);
  color: #fff;
}
.btn.success:hover:not(:disabled) {
  background: var(--color-success-dark);
}
.btn.danger {
  background: var(--color-danger);
  color: #fff;
}
.btn.danger:hover:not(:disabled) {
  opacity: 0.9;
}
</style>
